<?php

require_once("../phpGrid_Basic/conf.php");

 

function sec_session_start() {
    $session_name = 'sec_session_id';   // Set a custom session name
    $secure = SECURE;
    
    // This stops JavaScript being able to access the session id.
    $httponly = true;
    // Forces sessions to only use cookies.
    
    if (ini_set('session.use_only_cookies', 1) === FALSE) {
        header("Location: error.php?err=Could not initiate a safe session (ini_set)");
        exit();
    }

    // Gets current cookies params.
    $cookieParams = session_get_cookie_params();

    session_set_cookie_params($cookieParams["lifetime"],
        $cookieParams["path"], 
        $cookieParams["domain"], 
        $secure,
        $httponly);

    // Sets the session name to the one set above.
    session_name($session_name);
    session_start();            // Start the PHP session 
    session_regenerate_id();    // regenerated the session, delete the old one. 
}



function login($user, $password) {

	$mysqli = new mysqli(PHPGRID_DB_HOSTNAME, PHPGRID_DB_USERNAME, PHPGRID_DB_PASSWORD, PHPGRID_DB_NAME);

    // Using prepared statements means that SQL injection is not possible. 
    if ($stmt = $mysqli->prepare("SELECT NOMBRE_USUARIO, PASSWORD, ESTADO 
        FROM usuarios
       WHERE NOMBRE_USUARIO = ?
        LIMIT 1")) {

        $stmt->bind_param('s', $user);  // Bind "$email" to parameter.
        $stmt->execute();    // Execute the prepared query.
        $stmt->store_result();

        // get variables from result.
        $stmt->bind_result($db_user, $db_password,$estado);
        $stmt->fetch();

        // hash the password with the unique salt.
        $password = db_pass($password);
        if ($stmt->num_rows == 1) {
            // If the user exists we check if the password in the database matches
            // the password the user submitted.
						if ($estado == 'A' && $db_password == $password) {
							// Password is correct!
							// XSS protection as we might print this value
							$username = preg_replace("/[^a-zA-Z0-9_\-]+/", 
																		"", 
																		$db_user);
			
							$_SESSION['username'] = $username;
							$_SESSION['login_string'] = hash_pass($password);
			
							// Login successful.
    					$stmt->close();
							return true;
			
						} else {
							$stmt->close();
							return false;
						}
				}	
    }
}


function empresaOK($user, $empresa) {

	$mysqli = new mysqli(PHPGRID_DB_HOSTNAME, PHPGRID_DB_USERNAME, PHPGRID_DB_PASSWORD, PHPGRID_DB_NAME);

    // Using prepared statements means that SQL injection is not possible. 
    if ($stmt = $mysqli->prepare("SELECT EMPRESA 
        													FROM usuarios_empresas
       														WHERE NOMBRE_USUARIO = ?
       														AND EMPRESA = ?
       														AND ACTIVO = 1
        													LIMIT 1")) {

        $stmt->bind_param('si', $user, $empresa);
        $stmt->execute();   
        $stmt->store_result();

        // get variables from result.
        $stmt->bind_result($e);
        $stmt->fetch();

        if ($stmt->num_rows == 1) {

						// XSS protection as we might print this value
						$emp = preg_replace("/[^a-zA-Z0-9_\-]+/", 
																"", 
																$e);

						$_SESSION['empresa'] = $emp;

						// Login successful.
						return true;

				} else {
				
					return false;
				
				}
	//return true;
	}
}


function db_pass($password) {
	return  hash('sha512', $password . SALT);
}

function hash_pass($password) {
	// Get the user-agent string of the user.
	$user_browser = $_SERVER['HTTP_USER_AGENT'];
	 return hash('sha512', $password . $user_browser);
}


function login_check() {

    // Check if all session variables are set 
    if (isset($_SESSION['username'], $_SESSION['login_string'], $_SESSION['empresa'])) { 
        $login_string = $_SESSION['login_string'];
        $username = $_SESSION['username'];
        $empresa = $_SESSION['empresa'];

		$mysqli = new mysqli(PHPGRID_DB_HOSTNAME, PHPGRID_DB_USERNAME, PHPGRID_DB_PASSWORD, PHPGRID_DB_NAME);

        if ($stmt = $mysqli->prepare("SELECT password 
                                      FROM usuarios 
                                      WHERE nombre_usuario = ? LIMIT 1")) {

            // Bind "$user_id" to parameter. 
            $stmt->bind_param('s', $username);
            $stmt->execute();   // Execute the prepared query.
            $stmt->store_result();

            if ($stmt->num_rows == 1) {
                // If the user exists get variables from result.
                $stmt->bind_result($password);
                $stmt->fetch();
                $login_check = hash_pass($password);

                if ($login_check == $login_string) {
                    // Logged In!!!! 
                    return true;
                } else {
                    // Not logged in 
                    return false;
                }
            } else {
                // Not logged in 
                return false;
            }
        } else {
            // Not logged in 
            return false;
        }
    } else {
        // Not logged in 
        return false;
    }
}


function get_user_profile() {

    // Check if all session variables are set 
	$perfil = '';

    if (isset($_SESSION['username'])) {  
		$username = $_SESSION['username'];
		$mysqli = new mysqli(PHPGRID_DB_HOSTNAME, PHPGRID_DB_USERNAME, PHPGRID_DB_PASSWORD, PHPGRID_DB_NAME);

        if ($stmt = $mysqli->prepare("SELECT perfil 
                                      FROM usuarios 
                                      WHERE nombre_usuario = ? LIMIT 1")) {

            // Bind "$user_id" to parameter. 
            $stmt->bind_param('s', $username);
            $stmt->execute();   // Execute the prepared query.
            $stmt->store_result();

            if ($stmt->num_rows == 1) {
                // If the user exists get variables from result.
                $stmt->bind_result($perfil);
                $stmt->fetch();
            }
        }
    }
	return !empty($perfil) ? $perfil : 'USER';
}


function change_pass($oldPass, $newPass) {

    // Check if all session variables are set
    if (isset($_SESSION['username'])) { 
		$user = $_SESSION['username'];

		if (login($user, $oldPass)) {
			$password = db_pass($newPass);
			$mysqli = new mysqli(PHPGRID_DB_HOSTNAME, PHPGRID_DB_USERNAME, PHPGRID_DB_PASSWORD, PHPGRID_DB_NAME);
			$stmt = $mysqli->prepare("UPDATE usuarios SET password = ? WHERE nombre_usuario = ?");
			$stmt->bind_param('ss',$password,$user);
			$stmt->execute(); 			
			$stmt->close();

			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
}



function logout() {

	// Unset all session values 
	$_SESSION = array();

	// get session parameters 
	$params = session_get_cookie_params();

	// Delete the actual cookie. 
	setcookie(session_name(),
			'', time() - 42000, 

			$params["path"], 
			$params["domain"], 
			$params["secure"], 
			$params["httponly"]);

	// Destroy session 
	session_destroy();
}

?>